# -*- coding:utf-8 -*-
from __future__ import division
from dao.MySqlDAL import MySqlDAL
import datetime
from collections import defaultdict
__author__ = 'shudongma.msd(风骐)'

sqlUtil = MySqlDAL()

def getStockPrice(stock_id,date):
    global sqlUtil
    return sqlUtil.get_dimensions_one_row("SELECT stock_id,price,percent,updown,volume,turnover_rate,pe_lyr,pe_ttm,pb,mr,date FROM tb_stock_price WHERE stock_id='"+str(stock_id)+"' And date=str_to_date('"+date+"','%Y-%m-%d')")


holidays = ['2015-10-01','2015-10-02','2015-10-03','2015-10-04','2015-10-05','2015-10-06','2015-10-07','2016-01-01'
    ,'2016-01-02','2016-01-03','2016-02-07','2016-02-08','2016-02-09','2016-02-10','2016-02-11','2016-02-12'
    ,'2016-02-13','2016-04-02','2016-04-03','2016-04-04','2016-04-30','2016-05-01','2016-05-02','2016-06-09'
    ,'2016-06-10','2016-06-11']
# 判断是否是休息日
def isRestDay(strtime):
    global holidays
    if strtime in [t for t in holidays]:
        return True
    the_day = datetime.datetime.strptime(strtime, "%Y-%m-%d")
    week_day = datetime.date.isoweekday(the_day)
    return week_day in (6,7)

# 获取之后5个交易日数据
def getStockPriceIn5TradeDays(stock_id,strdate):
    global sqlUtil
    # 跳过休息日
    trade_days = []
    tmp_day = datetime.datetime.strptime(strdate, "%Y-%m-%d").date()
    while len(trade_days)<5:
        tmp_day = tmp_day + datetime.timedelta(days=1)
        if not isRestDay(str(tmp_day)):
            trade_days.append(str(tmp_day))

    sql = "SELECT stock_id,price,percent,updown,volume,turnover_rate,pe_lyr,pe_ttm,pb,mr,date FROM tb_stock_price WHERE stock_id='"+str(stock_id)+"' AND date in ("
    for day in trade_days:
        sql += "'"+day+"',"
    sql = sql[:-1]
    sql += ")"
    return sqlUtil.get_dimensions_rows(sql)


# 计算后5个交易日相对于当天价格指标的变化
def getChangeIn5TradeDays(stock_id,strdate=None,stock_info=None):
    if strdate != None:
        stock_info = getStockPriceIn5TradeDays(stock_id,strdate)
    elif stock_info == None:
        raise RuntimeError(u'strdate与stock_info不可同时为None')
    if stock_info[0]['percent'] == -1:
        stock_info[0]['percent'] = 0
    for i in xrange(1,len(stock_info)):
        if stock_info[i]['percent'] == -1:
            stock_info[i]['percent'] = 0
        stock_info[i]['percent'] = stock_info[i]['percent'] + stock_info[i-1]['percent']

    return stock_info

# print getChangeIn5Days('SH600000',"2015-10-04")



# 获取之后5个交易日数据
'''
    返回的数据形式是{stock_id:[5天的数据(从strdate的下一天开始5天) 按时间排序后的],...}
'''
def getAllStockPriceIn5TradeDays(strdate):
    global sqlUtil
    # 跳过休息日
    trade_days = []
    tmp_day = datetime.datetime.strptime(strdate, "%Y-%m-%d").date()
    while len(trade_days)<5:
        tmp_day = tmp_day + datetime.timedelta(days=1)
        if not isRestDay(str(tmp_day)):
            trade_days.append(str(tmp_day))

    sql = "SELECT stock_id,price,percent,updown,volume,turnover_rate,pe_lyr,pe_ttm,pb,mr,date FROM tb_stock_price WHERE date in ("
    for day in trade_days:
        sql += "'"+day+"',"
    sql = sql[:-1]
    sql += ") ORDER BY date"
    res = sqlUtil.get_dimensions_rows(sql)
    res_dict = defaultdict(list)  # {stock_id:[5天的数据 按时间排序后的]}
    for row in res:
        # 把 涨跌幅度为-1的当做没有涨跌
        if row['percent'] == -1:
            row['percent'] = 0
        res_dict[row['stock_id']].append(row)
    return res_dict


# 计算后5个交易日相对于当天价格指标的变化
'''
    返回的数据形式是{stock_id:[5天的数据 按时间排序后的],...}
'''
def getAllChangeIn5TradeDays(strdate=None,stock_info=None):
    if strdate != None:
        stock_info = getAllStockPriceIn5TradeDays(strdate)
    elif stock_info == None:
        raise RuntimeError(u'strdate与stock_info不可同时为None')
    for v in stock_info.values():
        for i in xrange(1,len(v)):
            v[i]['percent'] = v[i]['percent'] + v[i-1]['percent']
    return stock_info


def getAllStockInfo(strdate):
    global sqlUtil
    sql = "SELECT stock_id,price,percent,updown,volume,turnover_rate,pe_lyr,pe_ttm,pb,mr,date FROM tb_stock_price WHERE date='"+strdate+"'"
    res = sqlUtil.get_dimensions_rows(sql)
    res_dict = dict()
    for row in res:
        res_dict[row['stock_id']] = row
    return res_dict


# 过滤掉大跌大涨前一交易日的数据，不去训练，影响结果
def getSSEFilterDate(filtGabageDate=False):
    sql = "SELECT price,percent,date FROM tb_sse_info WHERE percent < -5 OR percent > 5"
    res = sqlUtil.get_dimensions_rows(sql)
    # 1-23的数据缺失
    filter_date = ['2016-01-23','2016-03-14','2016-04-13']
    if filtGabageDate:
        for row in res:
            tmp_day = row['date']-datetime.timedelta(days=1)
            while isRestDay(str(tmp_day)):
                filter_date.append(str(tmp_day))
                tmp_day -= datetime.timedelta(days=1)
            filter_date.append(str(tmp_day))
    # print set(filter_date)
    return set(filter_date)

# for row in getStockPriceIn5TradeDays('SH603085','2015-10-12'):
#     print row['percent']
# print ''
# for row in getChangeIn5TradeDays('SH603085','2015-10-12'):
#     print row['percent']

# for k,v in getAllChangeIn5TradeDays('2015-10-12').iteritems():
#     for row in v:
#         print k,row['percent']
# #
# for k,v in getAllStockPriceIn5TradeDays('2015-10-12').iteritems():
#     for row in v:
#         print k,row['percent']


# start_date = datetime.datetime.strptime('2015-10-08', "%Y-%m-%d").date()
# end_date = datetime.datetime.strptime('2015-12-30', "%Y-%m-%d").date()
#
# while start_date <= end_date:
#     for k,v in getAllChangeIn5TradeDays(str(start_date)).iteritems():
#         if len(v)<5:
#             print k,v[0]['date'],len(v)
#     start_date = start_date + datetime.timedelta(days=1)


# try:
#     getAllStockInfo('2016-01-10')['SH603866']
# except Exception,e:
#     print type(e).__name__ == 'KeyError'
#

# getSSEFilterDate(True)